package com.yogee.topseller.activity.login.presenter;

import android.app.Activity;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.activity.login.model.IRegisterModel;
import com.yogee.topseller.activity.login.model.bean.CheckBean;
import com.yogee.topseller.activity.login.model.bean.RegisterBean;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.activity.login.model.bean.UserBean;
import com.yogee.topseller.activity.login.model.impl.RegisterModel;
import com.yogee.topseller.activity.login.view.IRegisterView;
import com.yogee.topseller.activity.login.view.impl.RegisterActivity;
import com.yogee.topseller.activity.login.view.impl.ResetPsActivity;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.utils.AppUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册 设置密码 presenter
 *
 * @author BiHaidong
 * @date 2017-4-25
 */
public class RegisterPresenter {

    private IRegisterView mView;
    private IRegisterModel model;

    public RegisterPresenter(IRegisterView view) {
        this.mView = view;
    }

    /**
     * 检验用户唯一性
     * @param phone
     */
    public void checkUserUnique(String phone){
        model = new RegisterModel();
        model.checkUserUnique(phone).compose(mView.bindRecycler()).subscribe(new BaseSubscriber<>(new HttpOnNextListener<CheckBean>() {
            @Override
            public void onNext(CheckBean checkBean) {
                mView.loadingFinished();
                mView.returnCheck();
            }
        },mView));
    }

    
    public void newUserRegistration(String phone,String pwd,String steward) {
        model = new RegisterModel();
        model.newUserRegistration(phone,pwd,steward).compose(mView.bindRecycler()).subscribe(new BaseSubscriber<>(new HttpOnNextListener<RegisterBean>() {
            @Override
            public void onNext(RegisterBean userModel) {
                if ("1".equals(userModel.getResult())){
                    UserBean userBean = new UserBean();
                    userBean.setName(userModel.getName());
                    userBean.setSex(userModel.getSex());
                    userBean.setUserImg(userModel.getPhoto());
                    userBean.setUserId(userModel.getUserId());
                    userBean.setApprstats(userModel.getStatus());
                    userBean.setCommmoney(userModel.getCommmoney());
                    userBean.setUnablemoney(userModel.getUnablemoney());
                    userBean.setResult(userModel.getResult());
//                    AppUtil.saveUserInfo(((RegisterActivity)mView),userBean);
                    // 因注册和找回密码ui合并，ResetPsActivity
                    AppUtil.saveUserInfo(((ResetPsActivity)mView),userBean);
                    mView.loadingFinished();
                    mView.registerSuccess(userModel.getUserId(),userModel.getFlag(),userModel.getDay());
                }
            }
        }, mView));
    }



    /**
     * 向聚合数据平台发送短信验证码
     * @param phoneNum
     */
    public void sendSMS(final Activity activity, final String phoneNum, final int random){
        if (!NetUtil.isNetworkAvailable()){
            ToastUtils.showToast(activity,"网络中断了，请重新链接网络。");
            return;
        }
        if (!TextUtils.isEmpty(phoneNum)){
            new Thread() {
                public void run() {
                    try {
                        //准备获取短信验证码需要的基本信息
                        String result =null;
                        String url ="http://v.juhe.cn/sms/send";//请求接口地址
                        Map params = new HashMap();//请求参数
                        params.put("mobile",phoneNum);//接收短信的手机号码
                        params.put("tpl_id", Config.TPL_ID);//短信模板ID，请参考个人中心短信模板设置
                        params.put("tpl_value",Config.TPL_VALUE + random);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
                        params.put("key",Config.APPKEY);//应用APPKEY(应用详细页查询)
                        params.put("dtype","");//返回数据的格式,xml或json，默认json
                        try {
                            result =net(url, params, "GET");
                            Gson gson = new Gson();
                            final SMSbean returnBean = gson.fromJson(result,SMSbean.class);
                            //短信发送完成，更新UI操作
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mView.checkCode(returnBean);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", Config.USERAGENT);
            conn.setUseCaches(false);
            conn.setConnectTimeout(Config.DEF_CONN_TIMEOUT);
            conn.setReadTimeout(Config.DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, Config.DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }


    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }



}
